package com.zyy.joseata.mq;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.zyy.joseata.bo.MqMsgBO;
import com.zyy.joseata.config.SeataConfigProperties;
import com.zyy.joseata.constant.TxConst;
import com.zyy.joseata.constant.TxEventTypeConst;
import com.zyy.joseata.socket.SocketClient;
import com.zyy.joseata.util.ThreadLocalUtil;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Component
public class JoSeataMqTemplate {

    @Resource
    private Channel mqChannel;

    @Resource
    private SocketClient socketClient;

    @Resource
    private SeataConfigProperties seataConfigProperties;

    public <T> void send(String exchange,String routingKey,T payload) throws InterruptedException {

        MqMsgBO mqMsg= new MqMsgBO(exchange,routingKey,ThreadLocalUtil.getTxId(),payload);
        socketClient.send(TxEventTypeConst.MQ_TX_SEND,JSONObject.toJSONString(mqMsg));

        String jsonData = JSONObject.toJSONString(payload);

        AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder()
                .messageId(ThreadLocalUtil.getTxId()) // 设置消息ID
                .contentType("application/json") // 设置消息内容类型
                .headers(createHeaders()) // 设置自定义消息头
                .build();

        try {
            Long deliverTag = mqChannel.getNextPublishSeqNo();
            JoSeataMqAck.deliveryTagKeyMsgMap.put(deliverTag,mqMsg);
            mqChannel.basicPublish(exchange,routingKey,true,properties,jsonData.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static Map<String, Object> createHeaders() {
        Map<String, Object> headers = new HashMap<>();
        headers.put(TxConst.JOSEATA_TXID_HEADER, ThreadLocalUtil.getTxId());
        headers.put("custom-header2", "value2");
        return headers;
    }
}
